package me.android.library.common.orm.ability;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.function.Function;

public interface DS {
    SQLiteOpenHelper getHelper();

    default SQLiteDatabase readableDb() {
        return getHelper().getReadableDatabase();
    }

    default SQLiteDatabase writableDb() {
        return getHelper().getWritableDatabase();
    }

    default void execSQL(String sql, Object... params) {
        try (SQLiteDatabase db = writableDb()) {
            db.execSQL(sql, params);
        }
    }

    default Cursor rawQuery(String sql, String... selectionArgs) {
        try (SQLiteDatabase db = readableDb()) {
            return db.rawQuery(sql, selectionArgs);
        }
    }

    default void tx(Function<SQLiteDatabase, Exception> function) throws Exception {
        try (SQLiteDatabase db = writableDb()) {
            db.beginTransaction();
            try {
                Exception exception = function.apply(db);
                if (exception != null) {
                    throw exception;
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }
    }
}
